<template>
    <a-modal 
        v-model:open="open"
        :title="form.title"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            :label-col="{span: 4}"
            :wrapper-col="{span: 18}"
        >
            <a-form-item
                v-for="item in form.formItems"
                :key="item.name"
                :label="item.label"
                :name="item.name"
            >
                <component
                    v-if="item.type !== 'switch'"
                    :is="getComponent(item.type)"
                    v-bind="item.props"
                    v-model:value="formState[item.name]"
                ></component>
                <component
                    v-else
                    :is="getComponent(item.type)"
                    v-bind="item.props"
                    v-model:checked="formState[item.name]"
                ></component>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang='ts' setup>
import type { FormInstance } from 'ant-design-vue';
import { computed, defineProps, reactive, ref, watch } from 'vue';
const props = defineProps<{
    form: {
        title: string
        visible: boolean
        formItems: {
            type: string
            name: string
            label: string
            props?: any
            rules?: any[]
        }[]
        labelCol?: any
        wrapperCol?: any
        initialValues: any
        onOk?: any
        onCancel?: any
    },
    context: any
}>()

const formRef = ref<FormInstance>()
const formState = reactive({...props.form.initialValues})
const open = ref<boolean>(props.form.visible)
const rules = computed(() => {
    const result: any = {}
    props.form.formItems.forEach(item => {
        if(item.rules){
            result[item.name] = item.rules
        }
    })
    return result
})

watch(
    () => [props.form.visible, props.form.initialValues],
    ([value, data]) => {
        open.value = value;
        Object.assign(formState, data)
    }
)

const getComponent = (type: string) => {
    const componentMap : Record<string,string> = {
        input: 'a-input',
        select: 'a-select',
        switch: 'a-switch'
    }
    return componentMap[type] || 'a-input'
}

const handleOk = async () => {
    try {
        await formRef.value?.validate()
        props.form.onOk(formState)
        //重置表格和表单
        handleCancel()
        props.context.handleReset()
    } catch (error) {
        console.log(error);
    }
}

const handleCancel = () => { 
    formRef.value?.resetFields()
    open.value = false
}
</script>

<style scoped>
</style>